package top.linyuxb.lycloud.admin.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.linyuxb.lycloud.admin.constant.StatusEnum;
import top.linyuxb.lycloud.admin.entity.LyConfServerEntity;
import top.linyuxb.lycloud.admin.repository.LyConfServerRepository;
import top.linyuxb.lycloud.admin.service.ILyConfServerService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/8/8 16:17
 * @Desc:
 */
@Slf4j
@Service(value = "lyConfServerService")
public class LyConfServerServiceImpl implements ILyConfServerService {
    @Resource
    private LyConfServerRepository lyConfServerRepository;

    @Override
    public void refreshServer(LyConfServerEntity lyConfServer) {
        JSONObject json = new JSONObject();
        json.put("app", lyConfServer.getApp());
        json.put("env", lyConfServer.getEnv());
        String param = JSON.toJSONString(json);
        List<LyConfServerEntity> byStatusOrderByIdDesc = lyConfServerRepository.findByStatusOrderByIdDesc(StatusEnum.VALID.getType());
        for (LyConfServerEntity lyConfServer1 : byStatusOrderByIdDesc) {
            // 刷新网关服务
            String url1 = "http://" + lyConfServer1.getServerIp() + ":" + lyConfServer1.getServerPort() + "/lyGatewayClient/refreshServer";
            String data = this.doRefreshServer(url1, param, lyConfServer1.getUser(), lyConfServer1.getUserPassword());
            if (StringUtils.isBlank(data) || !Objects.equals(data, "SUCCESS")) {
                // 刷新rpc服务
                String url2 = "http://" + lyConfServer1.getServerIp() + ":" + lyConfServer1.getServerPort() + "/lyRpcClient/refreshServer";
                this.doRefreshServer(url2, param, lyConfServer1.getUser(), lyConfServer1.getUserPassword());
            }
        }
    }

    /**
     * 执行缓存刷新
     *
     * @param url
     * @param user
     * @param password
     */
    private String doRefreshServer(String url, String param, String user, String password) {
        Map<String, String> headers = new HashMap<>();
        headers.put("user", user);
        headers.put("password", password);
        try (HttpResponse execute = HttpRequest.post(url)
                .addHeaders(headers)
                .body(param)
                .timeout(1000)
                .execute()) {
            return execute.body();
        } catch (Exception e) {
            log.error("lyConfNodeService refreshConf error", e);
        }
        return null;
    }
}
